package com.cjk.foundation.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordUtil {

	public static byte[] encrypt(byte[] plain) {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(plain);
			return messageDigest.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] encrypt(byte[] salt, byte[] plain) {
		try {
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(salt);
			messageDigest.update(plain);
			return messageDigest.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String hexStr = "0123456789ABCDEF";

	public static byte[] hexStringToBytes(String hexString) {
		if ((hexString == null) || (hexString.equals(""))) {
			return null;
		}
		hexString = hexString.toUpperCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = ((byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[(pos + 1)])));
		}
		return d;
	}

	private static byte charToByte(char c) {
		return (byte) hexStr.indexOf(c);
	}

	public static void main(String[] args) {
//		String salt = "FRGSH7KKCGFJC5RCX2J5DM8CKNC46OCN";
//		byte[] dbmd5pwd = hexStringToBytes(MD5Util.encrypt("123456"));
//		byte[] a = encrypt(hexStringToBytes(salt), dbmd5pwd);
//		
//		System.out.println(MD5Util.encryptWithSalt(salt, MD5Util.encrypt("123456")));
//		
//		
//		byte[] web = hexStringToBytes("617c2574c05cfe9cd3e6680f3590d813");
//		
//		
//		System.out.println(MessageDigest.isEqual(web, a));
//		
//		
//		System.out.println(MessageDigest.isEqual(hexStringToBytes(MD5Util.encrypt("123456")), hexStringToBytes("e10adc3949ba59abbe56e057f20f883e")));

//		String salt = "uix8tf89mqpddnkgdf7th2dqo6zc2vvz";
//		String web_pwd = "c67499f03e939b80310af019f98e40df";
//		byte[] pwd_byte = encrypt("123456".getBytes());
//		byte[] pwd = encrypt(salt.getBytes(), pwd_byte);
//		System.out.println(MessageDigest.isEqual(hexStringToBytes(web_pwd), pwd));
		
//		//前端salt
//		String salt = "6e74ff4d2d18fed58e957abf85e62b72";
//		//前端 (pwd.md5 + salt).md5
//		String web_pwd = "65de3af2c4d573765fe16af04c977128";
//		byte[] pwd_byte = encrypt("123456".getBytes());
//		byte[] pwd = encrypt(salt.getBytes(), pwd_byte);
//		System.out.println(MessageDigest.isEqual(hexStringToBytes(web_pwd), pwd));
		

	
		
		byte[] salt = "sX5AcriEsjJTY2dHD2whY8WzC54eBfir".getBytes();
		byte[] webPwd = hexStringToBytes("9e102f9b0fd50318c3445a9cfb089637");
		byte[] pwd_byte = encrypt("123456".getBytes());
		byte[] pwd = encrypt(salt, pwd_byte);
		System.out.println(MessageDigest.isEqual(webPwd, pwd));
	}
}
